package com.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        HttpSession session = req.getSession();

        //已登陆
        if (session != null && session.getAttribute("username") != null) {
            filterChain.doFilter(req, resp);
            return;
        }

        String uri = req.getRequestURI();
        String loginSubmitURI = req.getContextPath() + "/Login";
        String loginPageURI = req.getContextPath() + "/login.html";

        //提交登陆信息不拦截
        if (loginSubmitURI.equals(uri)) {
            filterChain.doFilter(req, resp);
            return;
        }

        //访问登陆页面不拦截
        if (loginPageURI.equals(uri)) {
            filterChain.doFilter(req, resp);
            return;
        }

        //js，css等文件不拦截
        if (this.isNotInterceptFile(uri)) {
            filterChain.doFilter(req, resp);
            return;
        }

        req.setAttribute("message", "请先登录");
        req.setAttribute("requestURI", req.getContextPath() + "/login.html");
        req.getRequestDispatcher("/info.jsp").forward(req, resp);

    }

    private boolean isNotInterceptFile(String uri) {
        if (uri.endsWith(".css") || uri.endsWith(".js")) {
            return true;
        }
        return false;
    }

}
